import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Order } from 'src/schemas/order/order.interface';
import { CreateOrderDto } from 'src/dto/create-order.dto';
import { OrdersPaginationDto } from 'src/dto/orders-pagination.dto';
import { OrderState } from 'src/dto/order.dto';

@Injectable()
export class OrdersService {
  constructor(
    @InjectModel('Order') private readonly orderModel: Model<Order>,
  ) {}

  /**
   * 创建一个订单
   * @param user _id
   * @param createOrderDto 创建的订单部分信息
   */
  async create(user: string, createOrderDto: CreateOrderDto) {
    const { appointmentTime, amount, carwash, nickName, name } = createOrderDto;

    const createdOrder = new this.orderModel({
      nickName,
      appointmentTime,
      user,
      amount,
      carwash,
      name,
    } as Order);

    return createdOrder.save();
  }

  /**
   * 通过 _id 删除订单
   * @param _id _id
   */
  deleteById(_id: string) {
    return this.orderModel.deleteOne({ _id });
  }

  /**
   * 通过 _id 更新订单状态
   * @param _id _id
   * @param state 订单状态
   */
  updateState(_id: string, state: OrderState) {
    return this.orderModel.updateOne({ _id }, { state });
  }

  /**
   * 查询一些订单
   * @param staffsPaginationDto 查询条件
   */
  find(ordersPaginationDto: OrdersPaginationDto) {
    const { pageIndex, pageSize, keyword } = ordersPaginationDto;
    const reg = new RegExp(keyword, 'i');
    const conditions = {
      $or: [{ nickName: { $regex: reg } }, { name: { $regex: reg } }],
    };

    return this.orderModel
      .find(conditions, '-__v')
      .skip((pageIndex - 1) * pageSize)
      .limit(pageSize);
  }

  /**
   * 获得订单的总数
   */
  count(ordersPaginationDto: OrdersPaginationDto) {
    const { keyword } = ordersPaginationDto;
    const reg = new RegExp(keyword, 'i');
    const conditions = {
      $or: [{ nickName: { $regex: reg } }, { name: { $regex: reg } }],
    };

    return this.orderModel.find(conditions).countDocuments();
  }
}
